/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { previewer } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { FeaturedCmdDialogParams } from '@app-cad/types';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';
import { profileUiOptions } from '../common/common-ui-options';

enum RevolMode {
  COMPLETE = 'complete',
  ANGLE = 'angle',
  PLANE = 'plane',
  GEOMETRY = 'geometry',
  NEXT = 'next',
  MODEL = 'model',
}

enum AngleType {
  FORWARD = 'forward',
  REVERSE = 'reverse',
  BOTHWAY = 'bothway',
}

type FormData = {
  mode: RevolMode;
  profile: (pickedLineData | pickedFaceData)[];
  axis: pickedLineData;
  start: number;
  end: number;
  angleType: AngleType;
};

function Revol({ title, onClose, placement, props }: FeaturedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({
    mode: RevolMode.COMPLETE,
    profile: [],
    axis: null,
    start: 45,
    end: 45,
    angleType: AngleType.FORWARD,
  });
  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({
        mode: RevolMode.COMPLETE,
        profile: [],
        axis: null,
        start: 45,
        end: 45,
        angleType: AngleType.FORWARD,
      });
      return;
    }

    const { mode, profile, axis, start, end, angleType } = props.params;

    await initEditDependency([axis, ...profile]);

    const profileObj =
      profile?.length > 0 &&
      profile.map(
        (dxid) =>
          picker.generatePickObjByPickID(dxid) as
            | pickedLineData
            | pickedFaceData,
      );
    const axisObj =
      axis && (picker.generatePickObjByPickID(axis) as pickedLineData);

    const params = {
      mode: mode,
      profile: profileObj,
      axis: axisObj,
      start: start,
      end: end,
      angleType: angleType,
    };

    if (angleType === AngleType.BOTHWAY || angleType === AngleType.REVERSE) {
      params.start = `-${start}`;
    }

    setFormData(params);
  }, []);

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }
    await execute(true);
  };

  const isFormDataValid = () => {
    const { mode, profile, axis, start, end } = formData;

    if (mode === RevolMode.COMPLETE) {
      return profile?.length > 0 && axis != null;
    } else if (mode === RevolMode.ANGLE) {
      return (
        profile?.length > 0 && axis != null && start != null && end !== null
      );
    } else {
      return false;
    }
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const addDynamicParams = (
    params: Record<string, any>,
    dynamicParams: Record<string, any>,
  ) => {
    return { ...params, ...dynamicParams };
  };

  const execute = async (preview: boolean = false) => {
    const { mode, profile, axis, start, end, angleType } = formData;
    const profileIDs: string[] = profile.map((obj) => getIdOfPickedObj(obj));
    const axisParams = axis.edgeId;

    const params = {
      mode: mode,
      profile: profileIDs,
      axis: axisParams,
      angleType: angleType,
    };
    let dynamicParams = {};
    switch (mode) {
      case RevolMode.COMPLETE:
        dynamicParams = {
          start: 0,
          end: 360,
        };
        break;
      case RevolMode.ANGLE:
        if (angleType === AngleType.BOTHWAY) {
          dynamicParams = {
            start: `-${start}`,
            end: end,
          };
        } else if (angleType === AngleType.FORWARD) {
          dynamicParams = {
            start: 0,
            end: end,
          };
        } else if (angleType === AngleType.REVERSE) {
          dynamicParams = {
            start: `-${start}`,
            end: 0,
          };
        }

        break;
      case RevolMode.PLANE:
      case RevolMode.GEOMETRY:
      case RevolMode.MODEL:
        dynamicParams = {};
        break;
    }
    const validParams = addDynamicParams(params, dynamicParams);

    if (validParams.start === 0 && validParams.end === 0) {
      previewer.clear();
      return;
    }

    const res =
      props == null
        ? await wsApi.createRevol(validParams, preview)
        : await wsApi.setParams(props.shape, validParams, preview);

    if (preview) {
      await previewInCommand(res);
    }

    return res;
  };

  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute();

    exit();
  };

  const exit = () => {
    previewer.clear();
    onClose();
  };

  // =================

  const schema = useMemo(() => {
    const modeSchema = {
      type: 'string',
      title: '旋转类型',
      default: RevolMode.COMPLETE,
      oneOf: [
        {
          type: 'string',
          title: '完全旋转',
          const: RevolMode.COMPLETE,
        },
        {
          type: 'string',
          title: '给定角度',
          const: RevolMode.ANGLE,
        },
        // {
        //   type: 'string',
        //   title: '中间平面',
        //   const: RevolMode.PLANE,
        // },
        // {
        //   type: 'string',
        //   title: '成型到几何',
        //   const: RevolMode.GEOMETRY,
        // },
        // {
        //   type: 'string',
        //   title: '成形到下一面',
        //   const: RevolMode.NEXT,
        // },
        // {
        //   type: 'string',
        //   title: '成形到实体',
        //   const: RevolMode.MODEL,
        // },
      ],
    };

    const angleType = {
      type: 'string',
      title: '方向',
      default: AngleType.FORWARD,
      oneOf: [
        {
          type: 'string',
          title: '正向',
          const: AngleType.FORWARD,
        },
        {
          type: 'string',
          title: '反向',
          const: AngleType.REVERSE,
        },
        {
          type: 'string',
          title: '双向',
          const: AngleType.BOTHWAY,
        },
      ],
    };

    const angle = {
      end: {},
      start: {},
    };

    if (formData.angleType === AngleType.FORWARD) {
      angle.end = {
        type: 'number',
        title: '正向',
        default: 45,
        format: NumberInputFormat.Angle,
      };
      angle.start = {};
    } else if (formData.angleType === AngleType.REVERSE) {
      angle.start = {
        type: 'number',
        title: '反向',
        default: 45,
        format: NumberInputFormat.Angle,
      };
      angle.end = {};
    } else if (formData.angleType === AngleType.BOTHWAY) {
      angle.end = {
        type: 'number',
        title: '正向',
        default: 45,
        format: NumberInputFormat.Angle,
      };
      angle.start = {
        type: 'number',
        title: '反向',
        default: 45,
        format: NumberInputFormat.Angle,
      };
    }

    // 完全旋转
    if (formData.mode === RevolMode.COMPLETE) {
      return {
        properties: {
          mode: modeSchema,
          profile: {
            type: 'array',
            items: {
              type: 'string',
              enum: [],
            },
            uniqueItems: true,
            title: '轮廓',
            format: PickInputRJSFFormat.MultiPickContours,
          },
          axis: {
            type: 'string',
            title: '旋转轴',
            format: PickInputRJSFFormat.PickLine,
          },
        },
      };
    }

    // 给定角度
    if (formData.mode === RevolMode.ANGLE) {
      return {
        properties: {
          mode: modeSchema,
          profile: {
            type: 'array',
            items: {
              type: 'string',
              enum: [],
            },
            uniqueItems: true,
            title: '轮廓',
            format: PickInputRJSFFormat.MultiPickContours,
          },
          axis: {
            type: 'string',
            title: '旋转轴',
            format: PickInputRJSFFormat.PickLine,
          },
          angleType: angleType,
          end: angle.end,
          start: angle.start,
        },
      };
    }

    // 中间平面
    if (formData.mode === RevolMode.PLANE) {
      return {
        properties: {},
      };
    }

    // 成形到几何
    if (formData.mode === RevolMode.GEOMETRY) {
      return {
        properties: {},
      };
    }

    // 成形到下一面
    if (formData.mode === RevolMode.NEXT) {
      return {
        properties: {},
      };
    }

    // 成形到实体
    if (formData.mode === RevolMode.MODEL) {
      return {
        properties: {},
      };
    }
    return schema;
  }, [formData.mode, formData.angleType]);

  const { initEditDependency, previewInCommand } = useCommand('cmd-revol', {
    onClose,
    finishDraw: checkAndFinish,
  });

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={false}
      onClose={exit}
      title={title}
      placement={placement}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '请输入轮廓',
          'ui:autofocus': true,
          'ui:options': profileUiOptions,
        },
        axis: {
          'ui:placeholder': '请输入旋转轴',
        },
        angleType: {
          'ui:widget': 'radio',
          'ui:classNames': 'command-form__mode-switch',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdRevol: BaseCommand = {
  id: 'cmdRevol',
  label: 'command.revol',
  icon: 'commands/feature/revol',
  create: (label, onClose, props) => (
    <Revol
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
